import os
import json
import uuid
import requests
from datetime import datetime


def html_to_img(html_content):
    html2img_server_url = os.environ['html2img_server_url']
    gitee_apikey = os.environ['gitee_apikey']

    body = {
        'action': 'html2img',
        'args': {
            'html_content': html_content,
        }
    }

    try:
        res = requests.post(url=html2img_server_url, json=body, timeout=30, verify=False)
    except Exception as e:
        return '访问HTML网页截图服务失败：' + str(e)

    if res.status_code == 200:
        result = json.loads(res.text)
        if result['status'] != 'ok':
            return '访问HTML网页截图服务失败：' + result['value']
    else:
        return '访问HTML网页截图服务失败：' + '网络或服务器故障！'

    file_content= result['value'][len('data:image/png;base64,'):]
    file_path = datetime.now().strftime('%Y%m%d') + '/' + str(uuid.uuid4()).replace('-', '') + '.png'

    gitee_url = f'https://gitee.com/api/v5/repos/cubenet/images/contents/{file_path}'
    headers = {
        'Content-Type': 'application/json',
    }
    body = {
        'access_token': gitee_apikey,
        'content': file_content,
        'message': 'new file'
    }

    try:
        res = requests.post(gitee_url, headers=headers, json=body)
    except Exception as e:
        return '保存截图文件失败：' + str(e)

    if res.status_code != 201:
        return '保存截图文件失败!'

    img_url = f'![](/special/thirdfile/mcp-images/{file_path})'
    return img_url

